
#coding: utf8

import sys 
import os
import os.path 

cur_path = os.path.dirname(__file__)
parent_path = os.path.abspath(os.path.join(cur_path, '..'))
sys.path.append(parent_path)

import time
import random
import json
import Levenshtein
import pymongo
import redis

title_badword = [u'邮费', u'运费', u'差价' u'补拍' u'补差' u'专拍']


def title_rel(item1, item2):
    score = 10000/(1+Levenshtein.distance(item1['title'], item2['title']))
    for i in title_badword:
        if i in item2:
            score -= 5000
            break
    return score

def cats_rel(item1, item2, catsdata):
    cid1 = str(item1['cid'])
    cid2 = str(item2['cid'])
    if cid1 == cid2:
        return 5000
    if cid1 in catsdata and cid2 in catsdata[cid1]:
        return 5000/(1+catsdata[cid1].index(cid2))
    if cid2 in catsdata and cid1 in catsdata[cid2]:
        return 5000/(1+catsdata[cid2].index(cid1))
    return 1

def random_rel():
    return random.randint(10, 1000)

def relscore(item1, item2, catsdata):
    scores = random_rel() + title_rel(item1, item2) + cats_rel(item1, item2, catsdata)
    return scores

def item_correl(catsdata, item, items, i_key='_id'):
    tmpscores = []
    for ji in items:
        if ji == item:
            continue
        scores = relscore(item, ji, catsdata) 
        tmpscores.append((ji[i_key], scores))
    tmpscores.sort(lambda x, y: cmp(y[1], x[1]))
    tmpscores = [ k[0] for k in tmpscores[:10] ]
    return tmpscores

def correl(nick, mdb, catsdata):
    items = mdb.items.find({'nick':nick}, fields=['cid', 'title'])
    items.batch_size(100)
    items = list(items)
    ts = int(time.time())
    for it in items:
        rel_items = item_correl(catsdata, it, items)
        mdb.correl.save({'_id':it['_id'], 'rel':rel_items, 'ts':ts})

def test_editdist():
    print Levenshtein.distance(u'中国', u'中国人')
    print Levenshtein.distance('中国', '中国人')

def test_correl():
    mdb = pymongo.Connection(port=57324)
    catsdata = json.load(open('invert.cat.json'))
    #correl('zyy115104_2008', mdb.taogold, catsdata)
    correl('huiqing_shen', mdb.taogold, catsdata)

if __name__ == '__main__':
    test_correl()



